package fr.tocchisu.grepolis.requests;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimerTask;

import org.apache.commons.lang.StringUtils;

public abstract class AbstractHTTPRequest extends TimerTask {

	protected static final int SERVER_NUMBER = 47;

	private static final String SID = "4opskbcefcw0kwgk4sosw844s";
	protected static final String H = "5df6d963a8b";
	protected HttpURLConnection server;

	/**
	 * @param method
	 *            : String object for client method (POST, GET,...)
	 */
	public void connect(String method, String urlAsString) throws Exception {
		URL url = new URL(urlAsString);

		server = (HttpURLConnection) url.openConnection();
		server.setDoInput(true);
		server.setDoOutput(true);
		server.setRequestMethod(method);
		server.setRequestProperty("User-Agent", "    Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
		server.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
		server.setRequestProperty("Content-Length", "143");
		server.setRequestProperty("X-Requested-With", "XMLHttpRequest");
		server.setRequestProperty("Proxy-Connection", "keep-alive");
		server.setRequestProperty("Referer", "http://fr" + SERVER_NUMBER + ".grepolis.com/game/index?login=1");
		server.setRequestProperty(
				"Cookie",
				"__utma=1.1159197235.1326265465.1328307241.1328377495.49; __utmz=1.1327601593.35.3.utmcsr=fr.grepolis.com|utmccn=(referral)|utmcmd=referral|utmcct=/start; cid=1250068327; logged_in=true; PHPSESSID=the5tk6gjon8bu1uh9f09l7gc7; __utmc=1; __utmb=1.28.9.1328377785353; sid="
						+ SID);

		server.connect();
	}

	public void disconnect() {
		server.disconnect();
	}

	private void post(String s) throws Exception {
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
		bw.write(s, 0, s.length());
		bw.flush();
		bw.close();
	}

	protected void displayResponseHeader() {
		System.out.println("-----------HEAD------------");
		Iterator<Entry<String, List<String>>> iterator = server.getHeaderFields().entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<java.lang.String, java.util.List<java.lang.String>> entry = iterator.next();
			System.out.println(entry.getKey() + "=" + entry.getValue());
		}
	}

	protected void displayResponseBody() throws IOException {
		String line;
		System.out.println("-----------BODY------------");
		BufferedReader s = new BufferedReader(new InputStreamReader(server.getInputStream()));
		line = s.readLine();
		while (line != null) {
			System.out.println(line);
			line = s.readLine();
		}
		s.close();
	}

	protected void displayResponse() throws Exception {
		synchronized (AbstractHTTPRequest.class) {
			displayResponseHeader();
			displayResponseBody();
		}
	}

	protected String getPostDatas() {
		return "";
	};

	protected abstract String getURL();

	@Override
	public void run() {
		try {
			String fullURL = "http://fr" + SERVER_NUMBER + ".grepolis.com/game/" + getURL();
			connect("POST", fullURL);
			String postDatas = getPostDatas();
			if (StringUtils.isNotBlank(postDatas)) {
				post(postDatas);
			}
			displayResponse();
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			disconnect();
		}
	}

}
